from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
# Create your views here.
from post import models,postser
import random
from utils.authorization import MyAuthentication
from rest_framework import viewsets

class TopicPage(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'
    page_query_param = 'page'
#全部话题列表
class TopicList(ListAPIView):
    queryset = models.Topic.objects.filter(is_delete=False).order_by('-views')
    serializer_class = postser.TopicListSerializer
    pagination_class = TopicPage

    def get_serializer_context(self):
        # 为序列化器提供额外的上下文，此处添加当前请求的用户
        context = super().get_serializer_context()
        context['request'] = self.request
        return context
#话题榜
class Topic(APIView):
    authentication_classes =[MyAuthentication]
    def get(self,request):
        user=request.query_params.get('user')
        followed_topic_ids = models.UserTopic.objects.filter(user=user).values_list('topic_id', flat=True)
        topics=models.Topic.objects.filter(is_delete=False)
        topics=topics.exclude(id__in=followed_topic_ids)
        alltopic=random.sample(list(topics), 5)
        ser=postser.TopicSerializer(alltopic,many=True)
        return Response({"msg":"ok","data":ser.data})
#话题详情
class TopicDetail(APIView):
    def get(self,request):
        id=request.query_params.get("id")
        info=models.Topic.objects.filter(id=id,is_delete=False).first()
        ser=postser.TopicSerializer(info)
        data=ser.data
        #获取到当前话题的关注人数
        data["follows"]=models.UserTopic.objects.filter(topic=id).count()
        return Response({"msg":"ok","data":data})

#话题关注
#当前用户关注的话题
class UserTopicFollow(ListAPIView):
    authentication_classes = [MyAuthentication]
    queryset = models.UserTopic.objects.filter(is_delete=False)
    serializer_class = postser.UserTopicListSerializer
    pagination_class = TopicPage
    def get_queryset(self):
        user=self.request.query_params.get("user")
        return self.queryset.filter(user=user)
#当前话题的关注用户
class TopicFollow(ListAPIView):
    authentication_classes = [MyAuthentication]
    queryset = models.UserTopic.objects.filter(is_delete=False)
    serializer_class = postser.UserTopicSerializer
    pagination_class = TopicPage
    def get_queryset(self):
        id = self.request.query_params.get("id")
        return self.queryset.filter(topic=id)

#话题关注与取消
class AddTopicFollowView(APIView):
    authentication_classes = [MyAuthentication]
    def post(self,request):
        user=request.data.get("user")
        topic=request.data.get("topic")
        info=models.UserTopic.objects.filter(user=user,topic=topic).first()
        if info:
            info.delete()
            return Response({"code":200,"msg":"取消关注成功"})
        else:
            ser=postser.UserTopicSerializer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"code":200,"msg":"关注成功"})
            return Response({"code":400,"msg":ser.errors})
class PermissionViewSet(viewsets.ModelViewSet):
    queryset = models.Permission.objects.all()
    serializer_class = postser.PermissionSerializer

class PostView(APIView):
    def post(self,request):
        topics_data = request.data.pop('topics')
        imagedata=request.data.pop('images')
        ser=postser.PostSerializer(data=request.data)
        if ser.is_valid():
            post = ser.save()
            #添加话题
            post.topics.add(*topics_data)
            #添加图片
            for image in imagedata:
                models.Image.objects.create(post=post,image_url=image)
            return Response({"msg":"发布成功","code":200})
        return Response(ser.errors)

from rest_framework import status
from django.conf import settings
import oss2
class UploadImageView(APIView):
    def post(self, request, *args, **kwargs):
        image_file = request.FILES.get('image')

        if not image_file:
            return Response({'error': 'No image file provided'}, status=status.HTTP_400_BAD_REQUEST)

        # 上传图片到阿里云 OSS
        object_name = f'posts/{image_file.name}'
        settings.OSS_BUCKET.put_object(object_name, image_file)

        # 保存图片 URL 到数据库
        image_url = f'https://{settings.OSS_BUCKET_NAME}.{settings.OSS_ENDPOINT}/{object_name}'

        return Response({'image_url': image_url}, status=status.HTTP_201_CREATED)
